import type { Router, RouteRecordRaw } from "vue-router";
import { AllRoute } from "./routes/index";
import { useRouterPermissionStore } from "@/stores/modules/permission";

// 白名单
function whiteRouter() {}

// 递归查询系统存在的菜单导入（所需路由、子菜单带菜单的上一级路由）
// data: 查询的列表数组；value: 需要匹配的key值
const MatchedPaths = [];
const getSystemRouteTree = (data, value) => {
  if (MatchedPaths.includes(value)) return;
  // 查询到需要的路由
  for (const routeItem of data) {
    //挂钩权限且和value匹配的路由
    if (routeItem.path == value && routeItem.path != "/") {
      MatchedPaths.push(routeItem.path);
      return [{ ...routeItem, leafFlag: true }];
    }
    if (routeItem.children) {
      let exitRoute = getSystemRouteTree(routeItem.children, value);
      console.log(exitRoute, "exitRoute", value, routeItem.path);
      if (exitRoute) {
        MatchedPaths.push(exitRoute.path);
        return [
          {
            ...routeItem,
            children: [{ ...exitRoute, leafFlag: true }],
            leafFlag: false,
          },
        ];
      }
    }
  }
};

// 递归获取到的菜单返回路由
const getMenuTree = (treeData, outputRouteList = []) => {
  for (const treeItem of treeData) {
    const routeList = getSystemRouteTree(AllRoute, treeItem.path);

    if (routeList) outputRouteList = outputRouteList.concat(routeList);

    if (treeItem.children && treeItem.children.length > 0) {
      getMenuTree(treeItem.children, outputRouteList);
    }
  }
  return outputRouteList;
};

// 按照菜单初始化路由
function generateRouter(routeTree) {
  return getMenuTree(routeTree, []);
}

let auth = false;
// 按照权限添加菜单
export async function routerBeforeEach(router) {
  router.beforeEach(async (to, from, next) => {
    if (auth) {
      next();
      return;
    }

    // await useRouterPermissionStore().getMenuList();
    // const userMenuList = useRouterPermissionStore().menuList;
    auth = true;
    // const newRoutes = generateRouter(userMenuList);
    // console.log(newRoutes, "newRoutes", AllRoute);
    AllRoute.forEach((route) => router.addRoute(route));

    next(to.path);
    return true;
  });
}
